package im.route.api.util;

import im.route.api.exception.DecryptException;
import im.route.api.exception.EncryptException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
//import tech.kbtg.IntegrationModule.models.exception.DecryptException;
//import tech.kbtg.IntegrationModule.models.exception.EncryptException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

@Service
public class DesedeCryptSimpleHelper {

    private final String algorithm = "DESede";

    @Value("${paoc.encrypt.secretkey}")
    private String secretKey;

    public DesedeCryptSimpleHelper() {
    }

    public String encrypt(String infoContent) throws EncryptException {
        try {
            if (StringUtils.isNotBlank(infoContent)) {
                byte[] curBytes = infoContent.getBytes(StandardCharsets.UTF_8);
                byte[] cryptBytes = encrypt(curBytes, "");
                byte[] base64Bytes = Base64Util.encode(cryptBytes);

                return new String(base64Bytes, StandardCharsets.UTF_8);
            }

        } catch (Exception e) {
            throw new EncryptException("Fail to encrypt data！", e);
        }

        return "";
    }

    public String decrypt(String infoContent) throws DecryptException {
        try {
            if (StringUtils.isNotBlank(infoContent)) {
                byte[] curBytes = infoContent.getBytes(StandardCharsets.UTF_8);
                byte[] base64Bytes = Base64Util.decode(curBytes);
                byte[] cryptBytes = decrypt(base64Bytes, "");

                return new String(cryptBytes, StandardCharsets.UTF_8);
            }
        } catch (Exception e) {
            throw new DecryptException("Fail to decrypt data!", e);
        }

        return "";
    }

    public byte[] encrypt(byte[] data, String channel) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithm);
        byte[] keyBytes =
                Base64Util.decode(getSecretKey(channel).getBytes(StandardCharsets.UTF_8));
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes,
                algorithm));

        return cipher.doFinal(data);
    }

    public byte[] decrypt(byte[] data, String channel) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithm);
        byte[] keyBytes =
                Base64Util.decode(getSecretKey(channel).getBytes(StandardCharsets.UTF_8));
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes,
                algorithm));

        return cipher.doFinal(data);
    }

    private String getSecretKey(String channel) {
        return secretKey;
    }

    public String md5(String data, Charset encoding) {
        return DigestUtils.md5Hex(data.getBytes(encoding));
    }
}
